const mongoose = require('mongoose')
const { ObjectId } = mongoose.Types
const { ShopCart } = require('../../schema')

mongoose.connect('mongodb://127.0.0.1:27017/sportswear').then()
const shopCartCollection = mongoose.model('shopcart', ShopCart)

// 添加购物车
function insertShopCart ({ userid, proid, size, num }) {
    return new Promise(resolve => {
        shopCartCollection.find({
            userid,
            proid
        }).then(res => {
            if (res.length) {
                shopCartCollection.updateOne({
                    userid,
                    proid
                }, {
                    $inc: { num: num || 1 },
                    size: size || 'xl'
                }).then(res => {
                    resolve('更新购物车成功')
                })
            } else {
                const record = new shopCartCollection({
                    cartid: ObjectId(),
                    userid,
                    proid,
                    num: num || 1,
                    flag: true,
                    time: new Date(new Date().getTime() + 8 * 60 * 60 * 1000),
                    size: size || 'xl'
                })
                record.save().then(res => {
                    resolve('添加购物车成功')
                })
            }
        }).catch(err => {
            resolve('id格式不合法')
        })
    })
}

// 获取购物车列表
function getShopCartList (userid) {
    return new Promise(resolve => {
        try {
            shopCartCollection.aggregate([{
                $lookup: {
                    from: 'shops',
                    localField: 'proid',
                    foreignField: 'proid',
                    as: 'shop'
                }
            }, {
                $match: {
                    userid: ObjectId(userid)
                }
            }]).sort({ time: -1 }).then(res => {
                resolve(format(res))
            })
        } catch (e) {
            resolve('id不合法')
        }
    })
}

// 修改购物车选中状态
function modifyShopCartState (cartid, flag) {
    return new Promise(resolve => {
        shopCartCollection.updateOne({ cartid }, {
            flag
        }).then(res => {
            if (res.modifiedCount) {
                resolve('修改状态成功')
            } else {
                resolve('状态没有发生改变')
            }
        }).catch(err => {
            resolve('修改状态失败')
        })
    })
}

// 修改全部购物车选中状态
function modifyAllShopCartState (userid, flag) {
    return new Promise(resolve => {
        shopCartCollection.updateMany({
            userid
        }, {
            flag
        }).then(res => {
            if (res.modifiedCount) {
                resolve('修改全部选中状态成功')
            } else {
                resolve('全部选中状态保持不变')
            }
        }).catch(err => {
            resolve('修改全部状态失败')
        })
    })
}

// 修改购物车商品数量
function modifyShopCartNum (cartid, num) {
    return new Promise(resolve => {
        shopCartCollection.updateOne({ cartid }, {
            num
        }).then(res => {
            resolve('更新成功')
        }).catch(err => {
            resolve('更新失败')
        })
    })
}

// 移除选中的购物车
function removeCheckedShopCartList (userid) {
    return new Promise(resolve => {
        shopCartCollection.deleteMany({
            userid,
            flag: true
        }).then(res => {
            resolve(true)
        })
    })
}

// 获取选中的购物车
function getCheckedShopCartlist (userid) {
    return new Promise(resolve => {
        try {
            shopCartCollection.aggregate([{
                $lookup: {
                    from: 'shops',
                    localField: 'proid',
                    foreignField: 'proid',
                    as: 'shop'
                }
            }, {
                $match: {
                    userid: ObjectId(userid),
                    flag: true
                }
            }]).sort({ time: -1 }).then(res => {
                resolve(format(res))
            }).catch(err => {
                resolve(false)
            })
        } catch (e) {
            resolve(false)
        }
    })
}

// 删除一条购物车记录
function removeShopCartList (cartid) {
    return new Promise((resolve, reject) => {
        shopCartCollection.deleteOne({
            cartid
        }).then(res => {
            if (res.deletedCount) {
                resolve('移除一条购物车记录')
            } else {
                reject('没有找到购物车记录')
            }
        }).catch(err => {
            reject('出错了')
        })
    })
}

function format (data) {
    return data.map(item => {
        return {
            cartid: item.cartid,
            proid: item.proid,
            proname: item.shop[0] && item.shop[0].issale && item.shop[0].proname || '商品已经下架',
            originprice: item.shop[0] && item.shop[0].issale && item.shop[0].originprice || 0,
            discount: item.shop[0] && item.shop[0].issale && item.shop[0].discount || 0,
            img1: item.shop[0] && item.shop[0].issale && item.shop[0].swiper[0] || 'https://chengqige.com/svg/delete.png',
            stock: item.shop[0] && item.shop[0].issale && item.shop[0].stock || 0,
            issale: item.shop[0] && item.shop[0].issale || false,
            num: item.num,
            size: item.size,
            flag: item.flag,
        }
    })
}

module.exports = {
    insertShopCart,
    getShopCartList,
    modifyShopCartState,
    modifyAllShopCartState,
    modifyShopCartNum,
    getCheckedShopCartlist,
    removeCheckedShopCartList,
    removeShopCartList
}
